package org.ouwh.oowiki.ctrl;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.ouwh.fw.model.ModelReader;
import org.ouwh.fw.model.data.Struct;
import org.ouwh.oowiki.http.MyRequest;
import org.ouwh.oowiki.http.MyResponse;

public class ControllerDispatcher {
	private static Log log = LogFactory.getLog(ControllerDispatcher.class);
	static ModelReader reader = new ModelReader(ControllerDispatcher.class);

	public MyResponse handle(String controllerName, MyRequest request) throws Exception {
		MyResponse response = null;
		IController controller = null;
		try {
			controller = (AbstractController) reader.readModule(controllerName);
		} catch (ArrayIndexOutOfBoundsException e) {
			log.debug("controller not found: " + controllerName);
		}
		if (controller == null) {
			response = new MyResponse();
			Struct struct = new Struct("response");
			struct.addData("code", 404);
			struct.addData("message", "page not found");
			response.setResults(struct);
		} else {
			response = controller.execute(request);
			response.getResults().addData("code", 0);
		}
		return response;
	}
}
